let socketTask = ''
let is_open_socket = false
let timeout= 10000
let heartbeatInterval= null
let reconnectTimeOut= null
let closeFlag = true
var PublicUid = 0;


function setPublicUid(uid) {
    PublicUid = uid;
}

function createWebSocket() {
    try{
        // console.log('连接中...')
        socketTask = new WebSocket(server_socket_name)
        init(socketTask)
    } catch(e) {
        // console.log("连接异常")
        return null
    }
}

function init(socketTask) {
    socketTask.onopen = function() {
        // console.log('连接正常')
        clearTimeout(reconnectTimeOut)
        clearInterval(heartbeatInterval)
        is_open_socket = true;
        start();

    }

    socketTask.onmessage = function(res) {
        show_notice_index(JSON.parse(res.data))
        addCloseBut();
    }

    socketTask.onclose = function(res) {
        if(closeFlag){
            // console.log("已关闭")
            is_open_socket = false;
            reconnect();
        }else{
            closeFlag = true
        }
    }

}




function send(){
    if(!socketTask){
        removeWebsocket();
        return;
    }

    if(PublicUid > 0){
        socketTask.send(JSON.stringify({type:'pc', uid:PublicUid}))
    }else{
        removeWebsocket();
        return;
    }
}


function start(){
    heartbeatInterval = setInterval(()=>{
        send();
    },timeout)
}

function reconnect(){
    clearInterval(heartbeatInterval)
    if(!is_open_socket){
        reconnectTimeOut = setTimeout(()=>{
            createWebSocket();
        },timeout)
    }
}

function removeWebsocket() {
    clearInterval(heartbeatInterval);
    clearTimeout(reconnectTimeOut);
    socketTask.close();

    socketTask = ''
    is_open_socket = false
    timeout= 10000
    heartbeatInterval= null
    reconnectTimeOut= null
    closeFlag = false
}

